package com.luck.easyfoodbatch.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.dialog.ShowProgressDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.preview.ImageInfo;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.ArrayList;
import java.util.List;

/**
 * author：luck
 * project：LoveCare
 * package：com.tongyu.luck.lovecare.fragment
 * email：893855882@qq.com
 * data：16/8/10
 */
public class BaseFragment extends Fragment {
    protected SharedPreferences sp;
    protected SharedPreferences.Editor edit;
    protected Context mContext;
    protected View rootView;
    protected ImageButton left_back;
    protected TextView tv_title, right_title;
    public User user;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fc_base_main, container, false);
            left_back = (ImageButton) rootView.findViewById(R.id.left_back);
            tv_title = (TextView) rootView.findViewById(R.id.tv_title);
            right_title = (TextView) rootView.findViewById(R.id.right_title);
            init();
        }
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
    }

    /**
     * 初始化
     */
    protected void init() {
        mContext = getActivity();
        sp = getActivity().getSharedPreferences("userInfo", getActivity().MODE_PRIVATE);
        edit = sp.edit();
    }

    /**
     * 设置沉浸式状态栏
     */
    public void setPhoneStatus() {
        Window window = getActivity().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        window.setAttributes(layoutParams);
    }

    /**
     * 向下展开动画
     *
     * @param view
     */
    public void startAnimation(View view, boolean isLocation) {
        if (isLocation) {
            //相对于自己的高度往下平移
            TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            translate.setDuration(100);//动画时间500毫秒
            translate.setFillAfter(true);//动画出来控件可以点击
            view.startAnimation(translate);//开始动画
            view.setVisibility(View.VISIBLE);//设置可见
        } else {
            //相对于自己的高度往上平移
            TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f);
            translate.setDuration(100);
            translate.setFillAfter(false);//设置动画结束后控件不可点击
            view.startAnimation(translate);
            view.setVisibility(View.GONE);//隐藏不占位置
        }
    }


    /**
     * 防止连续点击跳转两个页面
     */
    protected long lastClickTime;

    protected boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 900) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(mContext, clz);
        startActivity(intent);
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz, Bundle bundle) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(mContext, clz);
        intent.putExtras(bundle);
        startActivity(intent);

    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity, 并关闭当前Activity
     * @author luck
     */
    protected void startFinishAct(Class clz, Bundle bundle) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(mContext, clz);
        intent.putExtras(bundle);
        startActivity(intent);
        getActivity().finish();
    }


    protected void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    protected boolean isCheckedLogin() {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user == null || TextUtils.isEmpty(user.getUid() + "")) {
            return false;
        }
        return true;
    }

    /**
     * 获得状态栏的高度
     */
    protected int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 查看图片 初始化启动动画参数
     * 单张图片
     */
    protected List<ImageInfo> initAnimImage(ImageView view, String path) {
        List<ImageInfo> list = new ArrayList<>();
        list.clear();
        ImageInfo info = new ImageInfo();
        info.imageViewWidth = view.getWidth();
        info.imageViewHeight = view.getHeight();
        info.setThumbnailUrl(path);// 缩略图地址
        info.setBigImageUrl(path);// 原图地址
        // 图片所在位置的x y 坐标
        int[] points = new int[2];
        view.getLocationInWindow(points);
        info.imageViewX = points[0];
        info.imageViewY = points[1] - getStatusHeight(mContext);
        list.add(info);
        return list;
    }

    protected List<ImageInfo> initAnimImage(View view, String path) {
        List<ImageInfo> list = new ArrayList<>();
        list.clear();
        ImageInfo info = new ImageInfo();
        info.imageViewWidth = view.getWidth();
        info.imageViewHeight = view.getHeight();
        info.setThumbnailUrl(path);// 缩略图地址
        info.setBigImageUrl(path);// 原图地址
        // 图片所在位置的x y 坐标
        int[] points = new int[2];
        view.getLocationInWindow(points);
        info.imageViewX = points[0];
        info.imageViewY = points[1] - getStatusHeight(mContext);
        list.add(info);
        return list;
    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public boolean isNetworkConnected() {
        try {
            ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();
            return ni != null && ni.isConnectedOrConnecting();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 加载提示
     */
    private ShowProgressDialog dialog;

    protected void showProgressDialog(String msg) {
        dialog = new ShowProgressDialog(getActivity());
        dialog.setContent(msg);
        dialog.show();
    }


    protected void hideShowProgress() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    protected void setTranslucentStatus(boolean on) {
        /**
         *
         * TODO 2016-9-24 20:09:21
         * TODO 亲测：能实现实现沉浸式状态栏
         * TODO  但是没有 isApplyStatusBarTranslucency这个方法返回值设为true来的方便
         *
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {  //  4.4
            //透明状态栏
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            SystemBarTintManager tintManager = new SystemBarTintManager(getActivity());
            // 激活状态栏
            tintManager.setStatusBarTintEnabled(true);
            // enable navigation bar tint 激活导航栏
            tintManager.setNavigationBarTintEnabled(true);
            //设置系统栏设置颜色
            //tintManager.setTintColor(R.color.red);
            //给状态栏设置颜色
            tintManager.setStatusBarTintResource(R.color.transparent);

        }
    }

    public static int getStatusBarHeight(Activity a) {
        int result = 0;
        int resourceId = a.getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = a.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
